package me.algo.array;

/**
 * @author guozheng
 * @date 2024/2/28
 */
public class A1 {


    public static void main(String[] args) {
        int[] m = {1, 2, 3, 4, 5};
        var x = 1;
        int i = binarySearch(m, x);
        System.out.println(i);
    }

    /**
     * 二分查找
     * @param arr
     * @param x
     * @return
     */
    public static int binarySearch(int[] arr, int x) {
        if (arr == null || arr.length == 0) {
            return -1;
        }
        // 定义左边指针和右边指针
        int leftIdx = 0;
        int rightIdx = arr.length - 1;
        while (leftIdx <= rightIdx) {
            int mid = (leftIdx + rightIdx) >>> 1;
            var midVal = arr[mid];
            if (midVal == x) {
                return mid;
            } else if (x < midVal) {
                rightIdx = mid - 1;
            } else {
                leftIdx = mid + 1;
            }
        }
        return -1;
    }
}
